const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const path = require("path");
const fs = require("fs");
require('express-async-errors');
const ResultJson = require("./model/ResultJson.js");
const AppConfig = require('./config/AppConfig.js');
const jwt = require("jsonwebtoken");
const exp = require('constants');

const app = express();
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())



//拦截器
// app.use((req,resp,next) => {
//     resp.setHeader("Access-Control-Allow-Origin","*");
//     resp.setHeader("Access-Control-Allow-Methods","*");
//     resp.setHeader("Access-Control-Allow-Headers","*");
//     next();
// })

app.use((req,resp,next) => {
    
    let pathValidata = AppConfig.excludePath.some(item => item.test(req.path));
    
    if(pathValidata){
        next()
    }else{
        if(req.method.toUpperCase() == "OPTIONS"){
            next()
        }else{
            // console.log('req请求信息',req);
            
            let token = req.headers.authorization;
            // console.log('token',token);
            if(token){
                jwt.verify(token,AppConfig.jwtKey,(error,decoded) => {
                    if(error){
                        resp.status(401).json(new ResultJson(false,"当前token失效"))
                    }else{
                        // console.log('1111',decoded);
                        next()
                    }
                })
            }else{
                resp.status(403).json(new ResultJson(false,"没有token，无权限"))
            }
            
        }
    }
})

app.use('/records',require('./routes/recordsRoute.js'))
app.use('/area',require('./routes/areaRoute.js'))
app.use('/adminInfo',require('./routes/adminInfoRoute.js'))
app.use('/adminPhoto',express.static(path.join(__dirname,"./adminPhoto")))
app.use('/stuInfo',require('./routes/stuInfo.js'))
// 总体错误处理
app.use((error,req,resp,next) => {
    resp.status(500).json(new ResultJson(false,"数据请求失败",error))
    next();
})


const server = http.createServer(app);
server.listen(3000,'0.0.0.0',() => {
    console.log('server is running ...')
    const deleteExcelFile = () => {
        let excelDirPath = path.join(__dirname,"./excelDir");
        let arr = fs.readdirSync(excelDirPath);
        for(let item of arr){
            let fileCreateTime = item.split("-")[0];
            if(Date.now() - fileCreateTime > 5 * 60 * 1000){
                fs.unlinkSync(path.join(excelDirPath,item));
            }
        }
    }
    deleteExcelFile();
    setInterval(deleteExcelFile,5 * 60 * 1000)
})